package com.example.st.service.impl;

import com.example.st.common.ResponseResult;
import com.example.st.dao.BpRepository;
import com.example.st.entity.Bp;
import com.example.st.service.BpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class BpServiceImpl implements BpService {

    @Autowired
    private BpRepository bpRepository;

    @Override
    public ResponseResult<List<Bp>> getAllBps() {
        List<Bp> bpList = bpRepository.findAll();
        return new ResponseResult<>(200, "Success", bpList);
    }

    @Override
    public ResponseResult<Bp> getBpById(Long pid) {
        Optional<Bp> bpOptional = bpRepository.findById(pid);
        if (bpOptional.isPresent()) {
            return new ResponseResult<>(200, "Success", bpOptional.get());
        } else {
            return new ResponseResult<>(404, "Bp not found", null);
        }
    }

    @Override
    public ResponseResult<List<Bp>> getBpByUid(Long uid) {
        List<Bp> bpList = bpRepository.getBpByUid(uid);
        if (bpList.isEmpty()) {
            return new ResponseResult<>(404, "Bp not found", null);
        } else {
            return new ResponseResult<>(200, "Success", bpList);
        }

    }

    @Override
    public ResponseResult<Bp> createBp(Bp bp) {
        Bp createdBp = bpRepository.save(bp);
        return new ResponseResult<>(200, "Bp created", createdBp);
    }

    @Override
    public ResponseResult<Bp> updateBp(Long pid, Bp bpDetails) {
        Optional<Bp> bpOptional = bpRepository.findById(pid);
        if (bpOptional.isPresent()) {
            Bp existingBp = bpOptional.get();
            existingBp.setUid(bpDetails.getUid());
            existingBp.setType(bpDetails.getType());
            existingBp.setDuration(bpDetails.getDuration());
            existingBp.setCost(bpDetails.getCost());
            existingBp.setOrigin(bpDetails.getOrigin());
            existingBp.setDestination(bpDetails.getDestination());
            Bp updatedBp = bpRepository.save(existingBp);
            return new ResponseResult<>(200, "Bp updated", updatedBp);
        } else {
            return new ResponseResult<>(404, "Bp not found", null);
        }
    }

    @Override
    public ResponseResult<Void> deleteBp(Long pid) {
        bpRepository.deleteById(pid);
        return new ResponseResult<>(200, "Bp deleted", null);
    }
}
